import React, { useState } from 'react';
import { Layout, Card, Form, Input, Button, Select, Typography } from 'antd';
import { UserOutlined, LockOutlined, IdcardOutlined } from '@ant-design/icons';
import './App.css';

// 导入antd样式
import 'antd/dist/reset.css';

const { Header, Content } = Layout;
const { Option } = Select;
const { Text } = Typography;

function App() {
  const [form] = Form.useForm();
  const [isLogin, setIsLogin] = useState(true); // 是否为登录模式
  const [userType, setUserType] = useState('student');
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: any) => {
    console.log("表单提交的值：", values);
    setLoading(true);

    try {
      let response;
      let requestBody;
      let apiUrl = '';

      if (isLogin) {
        // 处理不同角色的登录
        if (userType === 'student') {
          apiUrl = 'http://localhost:5000/api/studentLogin';
          requestBody = {
            student_no: values.student_no,
           
            password: values.password
          };
        } else if (userType === 'admin') {
          apiUrl = 'http://localhost:5000/api/adminLogin';
          requestBody = {
            username: values.username,
            password: values.password
          };
        } else if (userType === 'systemAdmin') {
          apiUrl = 'http://localhost:5000/api/sysAdminLogin';
          requestBody = {
            username: values.username,
            password: values.password
          };
        }

        // 发送请求
        response = await fetch(apiUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestBody),
        });

        const data = await response.json();
        console.log("后端返回的数据:", data);

        if (data.success) {
          alert(data.message); // 用 alert 替换 message.success
          console.log(localStorage.getItem('userInfo'));

          localStorage.setItem('userInfo', JSON.stringify(data.data));
          localStorage.setItem('userType', userType);

          // 跳转页面
          const redirectUrl =
            userType === 'student' ? '/student' :
            userType === 'admin' ? '/admin' :'/sysAdmin';
          window.location.href = redirectUrl;
        } else {
          alert(data.message || '登录失败'); // 用 alert 替换 message.error
        }
      } else {
        // 学生注册逻辑
        requestBody = {
          name: values.name,
          student_no: values.studentNo,
          gender: values.gender,
          id_card: values.id_card,
          password: values.password,
        };
        response = await fetch('http://localhost:5000/api/registerStudent', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestBody),
        });

        const data = await response.json();
        if (data.success) {
          alert('注册成功！'); // 用 alert 替换 message.success
          setIsLogin(true);
          form.resetFields();
        } else {
          alert(data.message || '注册失败'); // 用 alert 替换 message.error
        }
      }
    } catch (error) {
      alert('请求失败，请检查网络连接'); // 用 alert 替换 message.error
      console.error('请求错误:', error);
    } finally {
      setLoading(false);
    }
  };

  const switchMode = () => {
    setIsLogin(!isLogin);
    form.resetFields();
    if (isLogin) {
      setUserType('student');
      form.setFieldsValue({ userType: 'student' });
    }
  };

  const handleUserTypeChange = (value: string) => {
    setUserType(value);
    if (value !== 'student' && !isLogin) {
      setIsLogin(true); // 如果不是学生用户且当前为注册模式，切换到登录模式
    }
    form.resetFields(['username', 'student_no', 'password', 'confirmPassword']);
  };

  return (
    <Layout className="layout">
      <Header className="header">
        <h1 className="title">江软积公宝</h1>
      </Header>
      <Content className="content">
        <Card className="login-card" title={isLogin ? "用户登录" : "学生注册"} bordered={false}>
          <Form
            form={form}
            name={isLogin ? "login" : "register"}
            onFinish={onFinish}
            autoComplete="off"
            initialValues={{ userType: 'student' }}
          >
            <Form.Item name="userType" rules={[{ required: true, message: '请选择用户类型' }]}>
              <Select placeholder="请选择用户类型" onChange={handleUserTypeChange} disabled={!isLogin}>
                <Option value="student">学生</Option>
                <Option value="admin">社团管理员</Option>
                <Option value="systemAdmin">系统管理员</Option>
              </Select>
            </Form.Item>

            {isLogin ? (
              <>
                {userType === 'student' ? (
                  <Form.Item name="student_no" rules={[{ required: true, message: '请输入学号' }]}>
                    <Input prefix={<IdcardOutlined />} placeholder="请输入学号" />
                  </Form.Item>
                ) : (
                  <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                    <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
                  </Form.Item>
                )}

                <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }, { min: 6, message: '密码至少6个字符' }]}>
                  <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
                </Form.Item>

                {/* "注册"链接 */}
                {userType === 'student' && (
                  <Form.Item>
                    <Button type="link" onClick={switchMode} style={{ width: '100%' }}>
                      还没有账号？点击注册
                    </Button>
                  </Form.Item>
                )}
              </>
            ) : (
              <>
                <Form.Item name="name" rules={[{ required: true, message: '请输入姓名' }]}>
                  <Input prefix={<IdcardOutlined />} placeholder="请输入姓名" />
                </Form.Item>

                <Form.Item name="studentNo" rules={[{ required: true, message: '请输入学号' }, { pattern: /^\d{8,12}$/, message: '学号格式不正确（8-12位数字）' }]}>
                  <Input prefix={<IdcardOutlined />} placeholder="请输入学号" />
                </Form.Item>

                <Form.Item name="gender" rules={[{ required: true, message: '请选择性别' }]}>
                  <Select placeholder="请选择性别">
                    <Option value="male">男</Option>
                    <Option value="female">女</Option>
                    <Option value="other">其他</Option>
                  </Select>
                </Form.Item>

                <Form.Item name="id_card" rules={[{ required: true, message: '请输入身份证号' }, { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的18位身份证号码' }]}>
                  <Input prefix={<UserOutlined />} placeholder="请输入身份证号码" maxLength={18} />
                </Form.Item>

                <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }, { min: 6, message: '密码至少6个字符' }]}>
                  <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
                </Form.Item>

                {/* "登录"链接，放在注册按钮下方 */}
                <Form.Item>
                  <Button type="link" onClick={switchMode} style={{ width: '100%' }}>
                    已有账号？点击登录
                  </Button>
                </Form.Item>
              </>
            )}

            <Form.Item>
              <Button type="primary" htmlType="submit" block loading={loading}>
                {isLogin ? '登录' : '注册'}
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Content>
    </Layout>
  );
}

export default App;
